﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LightPersist;
using LightPersist.Storage;
using LightPersistTests;
using TestDomainModel;
using System.Collections.Specialized;
using LightPersist.Transactions;

namespace LightPersistTest.UI
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1 : Window
	{
		readonly ObservableCollection<FakeControl> collection1 = new ObservableCollection<FakeControl>();
		readonly ILightListProxy<FakeControl> collection2;

		public INotifyCollectionChanged List1 { get; set; }
		public INotifyCollectionChanged List2 { get; set; }

		public Window1()
		{
			var storage = new InmemoryStorage();
			storage.Connect(Guid.NewGuid().ToString());
			context = new LightPersistContext(storage, TestDomainModelMetainfo.Metainfo);
			root = context.RootClass<FakeRoot>();
			trh = context.BeginTransaction();
			collection2 = root.Children;
			List1 = collection1;
			List2 = collection2;
			//DataContext = this;
			InitializeComponent();
			listBox1.ItemsSource = collection1;
			listBox2.ItemsSource = collection2;
		}

		readonly LightPersistContext context;
		readonly FakeRoot root;
		TransactionGuard trh;

		private void Window_Loaded(object sender, RoutedEventArgs e)
		{
		}

		readonly static Random rnd = new Random();
		private void Button_Click(object sender, RoutedEventArgs e)
		{
			for(int i = 0; i < 5+rnd.Next(5); i++)
			{
				var action = rnd.Next(2);
				var id = rnd.Next(collection1.Count);
				switch(action)
				{
					case 0: // remove
						if(collection1.Count == 0)
						{
							continue;
						}
						collection1.RemoveAt(id);
						collection2.RemoveAt(id);
						break;
					case 1: // insert
						var item = context.Create<FakeControl>();
						collection1.Insert(id, item);
						collection2.Insert(id, item);
						break;
				}
			}
			trh.CommitTransaction();
			trh.Dispose();
			trh = context.BeginTransaction();
			
		}

	}
}
